package owlapps2012.klpfc;

import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;

public class OWLUtils {

	  public static void printOntologyAndImports(OWLOntologyManager manager, OWLOntology ontology) {
	        System.out.println("Loaded ontology:");
	        // Print ontology IRI and where it was loaded from (they will be the same)
	        printOntology(manager, ontology);

	        // List the imported ontologies
	        for(OWLOntology importedOntology : ontology.getImports()) {
	            System.out.println("Imports:");
	            printOntology(manager, importedOntology);
	        }
	    }

	    /**
	     * Prints the IRI of an ontology and its document IRI.
	     * @param manager The manager that manages the ontology
	     * @param ontology The ontology
	     */
	  public static void printOntology(OWLOntologyManager manager, OWLOntology ontology) {
	        IRI ontologyIRI = ontology.getOntologyID().getOntologyIRI();
	        IRI documentIRI = manager.getOntologyDocumentIRI(ontology);
	        System.out.println(ontologyIRI.toQuotedString());
	        System.out.println("    from " + documentIRI.toQuotedString());
	    }
	  
		
		public static String getLabel(OWLEntity ent, OWLOntology ont, String lang) 
		{
			String label = null;
			OWLAnnotationProperty ap = ont.getOWLOntologyManager().getOWLDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI());
			for(OWLOntology o : ont.getImportsClosure())
				for (OWLAnnotation annotation : ent.getAnnotations(o, ap))
				{
				    if (annotation.getValue() instanceof OWLLiteral) 
				    {
				        OWLLiteral val = (OWLLiteral) annotation.getValue();
				        if (val.hasLang(lang)) 
				       	 	label = val.getLiteral();
				    }
				}
			return label;
		}

		public static String getLabelPLIfExists(	OWLEntity ent, OWLOntology ont)
		{
			String res = getLabel(ent, ont, "pl");
			return res != null ?  res : ent.getIRI().getFragment();
		}
		
		public static String getLabelIfExists(	OWLEntity ent, OWLOntology ont, String lang)
		{
			String res = getLabel(ent, ont, lang);
			return res != null ?  res : ent.getIRI().getFragment();
		}
}
